package com.github.zengfr.easymodbus4j.example.processor;

import io.netty.util.internal.StringUtil;
import org.apache.commons.lang3.StringUtils;

import java.util.HashMap;
import java.util.Map;

public class DataMap {
    private static Integer len = 2000;

    private static Map<String,Integer[]> map = new HashMap<>();
    static {
        for(int i=0;i<len;i++){
            update(1,3,i,i);
        }
        for(int i=0;i<len;i++){
            update(2,3,i,i);
        }

    }

    public static void update(int slaveId,int functionCode,int startingAddress,Integer value){
        String identifier = slaveId + "-" + functionCode;
        Integer[] array = map.computeIfAbsent(identifier, k -> new Integer[len]);
        /*if(StringUtils.isEmpty(value)){

        }*/
        if(startingAddress >= 0 && startingAddress < len){
            array[startingAddress] = value;
        }
    }

    public static Integer getValue(int slaveId,int functionCode,int startingAddress){
        String identifier = slaveId + "-" + functionCode;
        Integer[] array = map.get(identifier);
        if(array != null && startingAddress < len){
            return array[startingAddress];
        }
        return 0;
    }

    public static Integer[] getBatchValue(int slaveId,int functionCode,int startingAddress,int quantity){
        Integer[] returnArray = new Integer[quantity];
        for(int i=0;i<quantity;i++){
            returnArray[i] = 0;
        }
        String identifier = slaveId + "-" + functionCode;
        Integer[] array = map.get(identifier);
        if(array != null && startingAddress < len && quantity < len){
            for(int i=0;i<quantity;i++){
                Integer d = array[startingAddress + i];
                returnArray[i] = d;
            }
            return returnArray;
        }
        return returnArray;
    }
}
